import re
import sys

def get_pin(cellName):
	f = open(cellName+".pin", 'r')
	all_line = f.readlines()
	is_find = False
	string = ""
	pin = []
	for line in all_line :
		if is_find :
			string += line
			if re.search('}', line):
				break
		if re.search(cellName, line):
			is_find= True
			string += line 


	string = string.split('{')[-1].split('}')[0]
	string = string.split('\n')
	for i in string:
		a = i.split(' ')[0].replace('\t', '')
		if a == '':
			pass
		else:
			pin.append(a)
	return pin

def option_PG_pin(alist):
	re_dict = {"power":[], "ground":[], "signal":[]}	
	for i in alist:
		if re.search(r'^VDD', i):
			re_dict["power"].append(i)
		elif re.search(r'^VSS', i):
			re_dict["ground"].append(i)
		elif re.search(r'GNDC', i):
			re_dict["ground"].append(i)
		else:
			re_dict["signal"].append(i)

	f = open("./include_option.conf", 'a')

	power = ""
	for i in re_dict["power"]:
		power += i+" "
	ground = ""
	for i in re_dict["ground"]:
		ground += i+" "

	f.write('lefExtOption -extractType "Block" -value { "PinsPowerNames" "'+power+'"}\n')
	f.write('lefExtOption -extractType "Block" -value { "PinsGroundNames" "'+ground+'"}\n')
	return re_dict

def option_AdjustBoundaryPinsDistByPinLayers(adict, metal, special_pin):
	f = open("./include_option.conf", 'a')
	re_string = ""
	
	metal_string = ""
	for i in range(metal):
		metal_string += "{M"+str(i)+" 0.4} "
	
	is_save = []
	for i in adict["signal"]:
		if '[' in i:
			s = i.split('[')[0]
			if s in is_save:
				pass
			else:
				re_string += "({"+s+"*} "+metal_string+") "
				is_save.append(s)
		elif '<' in i:
			s = i.split('<')[0]
			if s in is_save:
				pass
			else:
				re_string += "({"+s+"*} "+metal_string+") "
				is_save.append(s)
		else:
			if i in special_pin:
				pass
			else:
				re_string += "({"+i+"} "+metal_string+") "
	f.write('lefExtOption -extractType "Block" -value { "AdjustBoundaryPinsDistByPinLayers" "'+re_string+'"}\n')
	f.close()



####
topCell = sys.argv[1]
special_pin = ["VREF", "POC"]

####
# M0 to M13, NO AP layer
metal = int(sys.argv[2])

#### main
f = open("./include_option.conf", 'w')
f.close()

pin_list = get_pin(topCell)
adict = option_PG_pin(pin_list)
#option_AdjustBoundaryPinsDistByPinLayers(adict, metal, special_pin)